package com.eas.yunzhijia.easTodo;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

import static okhttp3.RequestBody.create;

@RestController
//@RequestMapping(value = "/message", produces = org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TodoController {


    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    OkHttpClient okHttpClient;

    Logger logger = Logger.getLogger(TodoController.class.getName());

    @Autowired
    TodoService todoService;


    @GetMapping(value = "/sso/login", produces = MimeTypeUtils.TEXT_HTML_VALUE)
    public RedirectView loginEas(@RequestParam(value = "username") String username,
                                 @RequestParam(value = "redirectTo",
                                         required = false,
                                         defaultValue = "/main.do") String redirectTo) {
        logger.info(todoService.login2(username, redirectTo).toString());
        return new RedirectView(todoService.login(username, redirectTo).toString());
    }


    @PostMapping(value = "/message/receive")
    public HttpEntity handlerMessageFromEAS(@org.springframework.web.bind.annotation.RequestBody WSMessage wsMessage) {

        System.out.println(wsMessage.toString());
        logger.info(wsMessage.toString());
        try {
            String accessToken = todoService.getToken();
            Request.Builder requestBuilder = new Request.Builder();
            HttpUrl.Builder builder = new HttpUrl.Builder();
            //https://www.yunzhijia.com/gateway/newtodo/open/generatetodo.json?accessToken=vDwuKPzg5aJdkkBgPEvdp2mvXNOUOk0E
            builder.scheme("https");
            builder.host("www.yunzhijia.com");
            builder.addPathSegment("gateway");
            builder.addPathSegment("newtodo");
            builder.addPathSegment("open");
            builder.addPathSegment("generatetodo.json");
            builder.addQueryParameter("accessToken", accessToken);
            requestBuilder.url(builder.build());

            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setAppId("500043950");
            messageEntity.setContent(wsMessage.getBody());
            messageEntity.setTitle(wsMessage.getTitle());
            messageEntity.setSourceId(wsMessage.getSourceID());
//            messageEntity.setContent("[轻应用Demo演示]请假单据需要您审批");
//            messageEntity.setTitle("测试代办");
//            messageEntity.setSourceId("123456");
            messageEntity.setHeadImg("https://yunzhijia.com/appsys/download.action?filename=500000813.png&type=9");
//            messageEntity.setSenderId(wsMessage.getSender());
            messageEntity.setSenderId("5a9e3bfce4b032a2d1d40e72");

            //TODO 换服务器的时候修改的内容
//            String url = "http://localhost:9090/eas/sso/login?username=" + wsMessage.getRecieveNumber() + "&redirectTo=http://10.30.100.71:6888/easweb/webviews/workflow/approve.jsp?assignmentId=" + wsMessage.getSourceID();


//            String url = "http://hrdev.dadimovie.com/eas/sso/login?" +
//                    "username= 10017091&redirectTo=http://36.110.112.109:6888/easweb/webviews/workflow/approve.jsp?assignmentId=233bbc64-57f6-492a-8e57-3e8716a77b9cWFWKITEM";
            //8a1d186d-43c8-4b25-97ea-498d55bab4a8WFWKITEM
            String url = "http://123.58.4.100:9999/?assignmentId=" + wsMessage.getSourceID();
//            String url = "http://10.30.100.71:9999/?assignmentId=" + wsMessage.getSourceID();
            messageEntity.setUrl(url);

            System.out.println(url + "-------url链接");
            List<MessageEntity.ParamsBean> paramsBeans = new ArrayList<>();
            MessageEntity.ParamsBean paramsBean = new MessageEntity.ParamsBean();
//            String openId = todoService.getOpenIdByNum(wsMessage.getRecieveNumber());
            paramsBean.setOpenId("5a9e3bfce4b032a2d1d40e93");
//            paramsBean.setOpenId(openId);
            MessageEntity.ParamsBean.StatusBean statusBean = new MessageEntity.ParamsBean.StatusBean();
            statusBean.setDO(0);
            statusBean.setREAD(1);
            paramsBean.setStatus(statusBean);
            paramsBeans.add(paramsBean);
            messageEntity.setParams(paramsBeans);
            String message = objectMapper.writeValueAsString(messageEntity);

            requestBuilder.post(create(MediaType.parse("application/json"), message));
//            okHttpClient.newCall(requestBuilder.build()).enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                    e.printStackTrace(System.err);
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//
//                }
//            });
            Response response = okHttpClient.newCall(requestBuilder.build()).execute();
            okhttp3.ResponseBody responseBody = response.body();
            if (response.isSuccessful() && responseBody != null) {

                return ResponseEntity.ok(responseBody.string());
            } else {
                throw new IllegalArgumentException("appId或openId不正确");
            }
        } catch (IOException | ExecutionException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }


    @GetMapping
    public RedirectView linkToAssignmentPage(@RequestParam(required = false) String ticket, @RequestParam String assignmentId) {
        System.out.println("---------------------ticket----" + ticket);
        System.out.println("---------------------name------" + assignmentId);

        try {
            return new RedirectView(todoService.buildAssignmentPageSSOLink(ticket, assignmentId));
        } catch (IOException | ExecutionException e) {
            e.printStackTrace();
            return new RedirectView("http://www.baidu.com");
        }
    }

    @PostMapping(value = "/public")
    public HttpEntity sendPublicMessage() {
        try {
            todoService.sendPublicKey();
            return ResponseEntity.ok().build();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

}


//http://localhost:9090/eas/sso/login?username= 10017011&redirectTo=http://10.30.100.71:6888/easweb/webviews/workflow/approve.jsp?assignmentId=233bbc64-57f6-492a-8e57-3e8716a77b9cWFWKITEM